import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/main/Login'
import Main from '@/main/Main'
import http from '@/common/httpUtil';

Vue.use(Router)


const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
];

let main = {
  path: '/main',
  name: 'Main',
  component: Main,
  children:[],
};


const router =  new Router({
  isFetched:false,
  routes:routes,
});


router.beforeEach((to,from,next)=>{
  if(to.name == 'Login'){
    next()
  }
  else if(router.options.isFetched == false){
    
    http.get("/admin/user/menuList").then(resp=>{
      //保存用户权限
      localStorage.setItem(window.sysModel.userPermissions,JSON.stringify(resp.data.perms || []));

      router.options.isFetched = true;
      const menus = resp.data.menuList || [];

      var list = [];
      //动态创建路由
      for(let i=0;i<menus.length;i++){
        let menu = menus[i];
        let submenus = menu.subMenus || [];

        submenus.forEach((ele,index)=>{
            let path = ele.path.replace(/\//g,'-');
            let filePath = ele.path;
            list.push({
              path:'/' + path,
              meta:{
                name:ele.name + '',
              },
              component: ()=>import(`@/${filePath}`),
            });
            ele.path = '/' + path;
        });
      }

      main.children = list;
      router.addRoutes([main]);
      //存储菜单项
      localStorage.setItem(window.sysModel.menuList,JSON.stringify(menus));

      next(to);
    }).catch(e=>{
      router.push('/');
    });
    
  }
  else{
    next();
  }
});

export default router
